package com.binhthuan.catechist.client.content.manage;

import java.util.LinkedHashMap;

import com.binhthuan.catechist.client.AbstractContent;
import com.binhthuan.catechist.client.ContentFactory;
import com.binhthuan.catechist.client.ECApplication;
import com.binhthuan.catechist.client.ECIcons;
import com.binhthuan.catechist.client.component.PopupDialog;
import com.binhthuan.catechist.client.data.AttendanceStatusDS;
import com.binhthuan.catechist.client.data.ScheduleStatusDS;
import com.binhthuan.catechist.client.data.TraineeStatusDS;
import com.binhthuan.catechist.client.data.TrainerStatusDS;
import com.binhthuan.catechist.client.form.AbstractForm;
import com.binhthuan.catechist.client.form.StatusForm;
import com.binhthuan.catechist.client.grid.StatusGrid;
import com.binhthuan.catechist.shared.Utilities;
import com.binhthuan.catechist.shared.constant.Service;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Dialog;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.events.DataArrivedEvent;
import com.smartgwt.client.widgets.grid.events.DataArrivedHandler;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class ManageStatus extends AbstractContent {

    public static class Factory implements ContentFactory {

        private static Factory instance;
        private String id;

        private Factory() {
            if (id == null) {
                id = Utilities.generateID(ManageStatus.class.getName());
            }
        }

        /**
         * @return the instance
         */
        public static Factory getInstance() {
            if (instance == null) {
                instance = new Factory();
            }

            return instance;
        }

        @Override
        public boolean checkCertificated(long securityCode) {
            return true;
        }

        @Override
        public AbstractContent create() {
            ManageStatus content = new ManageStatus();
            return content;
        }

        @Override
        public String getID() {
            return id;
        }

        @Override
        public String getIcon() {
            return null;
        }

        @Override
        public String getTitle() {
            return ECApplication.getConstants().status();
        }
    }

    private PopupDialog inputDialog;
    private TabSet detailTabset;
    private StatusGrid reportGrid;
    private StatusForm updateEditor;
    private StatusForm createEditor;
    private SelectItem statusSelector;
    private Label unselectedLabel;
    private Label totalItems;

    @Override
    public Canvas getContentPanel() {
        ensureCreateDialog();
        ensureUpdateEditor();
        VLayout mainLayout = new VLayout();
        mainLayout.setWidth100();
        mainLayout.setHeight100();

        SectionStack stack = new SectionStack();
        stack.setWidth100();
        stack.setHeight100();
        stack.setAnimateSections(true);
        stack.setShowEdges(true);
        stack.setVisibilityMode(VisibilityMode.MULTIPLE);

        final SectionStackSection reportSection = new SectionStackSection("a");
        reportSection.setCanCollapse(false);
        reportSection.setExpanded(true);

        totalItems = new Label();
        totalItems.setAlign(Alignment.RIGHT);

        final ToolStripButton addButton = new ToolStripButton();
        addButton.setIcon(ECIcons.getIcon("add.png"));
        addButton.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                ensureCreateDialog().show();
            }
        });

        final ToolStripButton deleteButton = new ToolStripButton();
        deleteButton.setIcon(ECIcons.getIcon("delete.png"));
        deleteButton.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                reportGrid.removeSelectedItems(true);
            }
        });

        ToolStrip toolStrip = new ToolStrip();
        toolStrip.addButton(addButton);
        toolStrip.addButton(deleteButton);

        statusSelector = new SelectItem();
        statusSelector.setShowTitle(false);
        statusSelector.setDefaultToFirstOption(true);
        statusSelector.setWrapTitle(false);
        statusSelector.addChangedHandler(new ChangedHandler() {

            @Override
            public void onChanged(ChangedEvent event) {
                DataSource ds = getDataSource(statusSelector.getValue().toString());

                reportGrid.setDataSource(ds);
                reportGrid.fetchData();

                createEditor.setDataSource(ds);
                updateEditor.setDataSource(ds);

                reportSection.setTitle(getSelectedStatusName());
                addButton.setPrompt(ECApplication.getMessages().addItem(getSelectedStatusName()));
                deleteButton.setPrompt(ECApplication.getMessages().deleteItem(getSelectedStatusName()));
                inputDialog.setTitle(ECApplication.getMessages().addItem(getSelectedStatusName()));
            }
        });
        statusSelector.setValueMap(getStatusTypes());

        DynamicForm form = new DynamicForm();
        form.setHeight(1);
        form.setWidth(75);
        form.setNumCols(1);
        form.setFields(statusSelector);

        reportGrid = new StatusGrid();
        reportGrid.setAutoFetchData(false);
        reportGrid.addDataArrivedHandler(new DataArrivedHandler() {

            @Override
            public void onDataArrived(DataArrivedEvent event) {
                totalItems.setContents(ECApplication.getMessages().numberOfResult(reportGrid.getTotalRows()));
                reportGrid.deselectAllRecords();
                updateDetailPanel();
            }
        });

        reportGrid.addRecordClickHandler(new RecordClickHandler() {

            @Override
            public void onRecordClick(RecordClickEvent event) {
                updateDetailPanel();
            }
        });

        reportSection.setItems(reportGrid);
        reportSection.setControls(totalItems, form, addButton, deleteButton);

        detailTabset = new TabSet();
        detailTabset.setWidth100();
        detailTabset.setHeight(165);

        unselectedLabel = new Label();
        unselectedLabel.setHeight100();
        unselectedLabel.setWidth100();
        unselectedLabel.setAlign(Alignment.CENTER);
        unselectedLabel.setContents(ECApplication.getMessages().noItemToDisplay());

        Tab editTab = new Tab(ECApplication.getConstants().edit());
        editTab.setIcon(ECIcons.getIcon("edit.png"));
        editTab.setWidth(100);
        editTab.setPane(unselectedLabel);

        detailTabset.setTabs(editTab);

        SectionStackSection detailSection = new SectionStackSection(ECApplication.getConstants().detail());
        detailSection.setExpanded(true);
        detailSection.addItem(detailTabset);

        stack.setSections(reportSection, detailSection);
        mainLayout.setMembers(stack);

        mainLayout.addDrawHandler(new DrawHandler() {

            @Override
            public void onDraw(DrawEvent event) {
                statusSelector.fireEvent(new ChangedEvent(null));
            }
        });
        return mainLayout;
    }

    @Override
    protected String getHelpContent() {
        return "This is help content for manage area page";
    }

    public Dialog ensureCreateDialog() {
        if (inputDialog == null) {
            inputDialog = new PopupDialog();

            createEditor = new StatusForm() {

                @Override
                protected void onUpdateSuccess() {
                    editNewRecord();
                    inputDialog.closeClick();
                }
            };
            inputDialog.addItem(createEditor);
        }

        return inputDialog;
    }

    public AbstractForm ensureUpdateEditor() {
        if (updateEditor == null) {
            updateEditor = new StatusForm();
        }

        return updateEditor;
    }

    public void updateDetailPanel() {
        if (reportGrid.anySelected()) {
            ensureUpdateEditor().clearErrors(false);
            ensureUpdateEditor().editRecord(reportGrid.getSelectedRecord());

            detailTabset.updateTab(0, ensureUpdateEditor());
        } else {
            detailTabset.updateTab(0, unselectedLabel);
        }
    }

    public LinkedHashMap<String, String> getStatusTypes() {
        LinkedHashMap<String, String> types = new LinkedHashMap<String, String>();
        types.put(AttendanceStatusDS.getInstance().getID(), ECApplication.getConstants().attendanceStatus());
        types.put(ScheduleStatusDS.getInstance().getID(), ECApplication.getConstants().scheduleStatus());
        types.put(TraineeStatusDS.getInstance().getID(), ECApplication.getConstants().traineeStatus());
        types.put(TrainerStatusDS.getInstance().getID(), ECApplication.getConstants().trainerStatus());

        return types;
    }

    public DataSource getDataSource(String id) {
        DataSource ds = DataSource.getDataSource(id);
        if (ds == null) {
            if (Service.ATTENDANCE_STATUS.equals(id)) {
                ds = AttendanceStatusDS.getInstance();
            } else if (Service.SCHEDULE_STATUS.equals(id)) {
                ds = ScheduleStatusDS.getInstance();
            } else if (Service.TRAINEE_STATUS.equals(id)) {
                ds = TraineeStatusDS.getInstance();
            } else if (Service.TRAINER_STATUS.equals(id)) {
                ds = TrainerStatusDS.getInstance();
            }
        }
        return ds;
    }

    public String getSelectedStatusName() {
        String name = statusSelector.getValue().toString();
        if (Service.ATTENDANCE_STATUS.equals(name)) {
            name = ECApplication.getConstants().attendanceStatus();
        } else if (Service.SCHEDULE_STATUS.equals(name)) {
            name = ECApplication.getConstants().scheduleStatus();
        } else if (Service.TRAINEE_STATUS.equals(name)) {
            name = ECApplication.getConstants().traineeStatus();
        } else if (Service.TRAINER_STATUS.equals(name)) {
            name = ECApplication.getConstants().trainerStatus();
        }
        return name;
    }

    /* (non-Javadoc)
     * @see com.binhthuan.catechist.client.AbstractContent#getPrintPreviewPanel()
     */
    @Override
    protected Canvas getPrintPreviewPanel() {
        return reportGrid;
    }
}
